package com.ali.juejin.utils

import android.animation.Animator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton

class FabScrollBehavior: FloatingActionButton.Behavior, Animator.AnimatorListener {
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    private var isShowAnimate = false

    override fun onStartNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: FloatingActionButton,
        directTargetChild: View,
        target: View,
        axes: Int,
        type: Int
    ): Boolean {
        return axes == ViewCompat.SCROLL_AXIS_VERTICAL
    }

    override fun onNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: FloatingActionButton,
        target: View,
        dxConsumed: Int,
        dyConsumed: Int,
        dxUnconsumed: Int,
        dyUnconsumed: Int,
        type: Int,
        consumed: IntArray
    ) {
        super.onNestedScroll(
            coordinatorLayout,
            child,
            target,
            dxConsumed,
            dyConsumed,
            dxUnconsumed,
            dyUnconsumed,
            type,
            consumed
        )
        if (dyConsumed > 0 && !isShowAnimate) { // 向下滑动
            animateHide(child);
        } else if (dyConsumed < 0 && !isShowAnimate) { // 向上滑动
            animateShow(child);
        }
    }

    private fun animateHide(fab:FloatingActionButton){
        fab.animate().scaleX(0f).scaleY(0f).setListener(this).start()
    }

    private fun animateShow(fab:FloatingActionButton){
        fab.animate().scaleX(1f).scaleY(1f).start()
    }

    override fun onAnimationRepeat(p0: Animator?) {
    }

    override fun onAnimationEnd(p0: Animator?) {
        isShowAnimate = false
    }

    override fun onAnimationCancel(p0: Animator?) {
    }

    override fun onAnimationStart(p0: Animator?) {
        isShowAnimate = true
    }

}